package io.sdl.controller;


import cn.hutool.core.date.DateTime;
import io.sdl.common.constant.UrlConstants;
import io.sdl.common.utils.*;
import io.sdl.dto.SdlPatientsDTO;
import io.sdl.entity.SdlPatientsArchivesEntity;
import io.sdl.entity.SdlPatientsEntity;
import io.sdl.entity.TokenEntity;
import io.sdl.entity.UserEntity;
import io.sdl.service.SdlPatientsArchivesService;
import io.sdl.service.SdlPatientsService;
import io.sdl.service.TokenService;
import io.sdl.service.UserService;
import io.sdl.vo.BackPhotoVo;
import io.sdl.vo.XPhotoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.util.*;

/**
 * @author Dc 1211734836@qq.com
 * @since 1.0.0 2025-03-28
 */
@RestController
@RequestMapping("/api")
@Tag(name = "")
public class ApiSdlPatientsController {

	@Autowired
	private SdlPatientsService sdlPatientsService;

	@Autowired
	private TokenService tokenServicel;

	@Autowired
	private UserService userService;

	@Autowired
	private SdlPatientsArchivesService sdlPatientsArchivesService;


	@GetMapping("getPatients")
	@Operation(summary = "获取患者列表")
	public Result<PageUtils> getPatients(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
		if (params.get("token") != null && !params.get("token").equals("")) {
			TokenEntity byToken = tokenServicel.getByToken(params.get("token").toString());

			UserEntity user = userService.getUserByUserId(byToken.getUserId());

			Query query = new Query(params);
			//获取总条数
			Integer total = sdlPatientsService.getNum(user.getMobile());

			List<SdlPatientsDTO> patients = sdlPatientsService.getPatientsByUserId(user.getMobile(), query.getPage(), query.getLimit());

			patients.forEach(p -> {
				//获取患者年龄
				Integer year = Integer.valueOf(String.format("%tY", p.getBirthDate()));
				Integer nowYear = Integer.valueOf(String.format("%tY", DateTime.now()));
				p.setAge(nowYear - year);

				//根据患者id获取指定图片
				Long patientsId = p.getPatientsId();
				//获取患者档案的背部照片和X光片
				SdlPatientsEntity patientsEntity = sdlPatientsService.selectById(patientsId);
				//获取复查记录的背部照片和X光片
				SdlPatientsArchivesEntity sdlPatientsArchivesEntity = sdlPatientsArchivesService.selectByPatientId(patientsId);
				//新建照片集合
				List<String> strings = new ArrayList<>();
				strings.add(UrlConstants.getProductionUrl() + patientsEntity.getRearPhoto());
				strings.add(sdlPatientsArchivesEntity != null ? UrlConstants.getProductionUrl() + sdlPatientsArchivesEntity.getRearPhoto() : null);
				strings.add(UrlConstants.getProductionUrl() + patientsEntity.getXPhoto());
				strings.add(sdlPatientsArchivesEntity != null ? UrlConstants.getProductionUrl() + sdlPatientsArchivesEntity.getXPhoto() : null);

				p.setPhotos(strings);
			});
			PageUtils PageUtils = new PageUtils(patients, total, query.getLimit(), query.getPage());

			return new Result<PageUtils>().ok(PageUtils);
		}

		return new Result<PageUtils>().error(400, "长时间未操作,请重新登录");
	}


	@GetMapping("getPatientsById")
	@Operation(summary = "根据id获取患者信息")
	public Result getPatientsById(@Parameter(hidden = true) @RequestParam Map<String, Object> params) {
		TokenEntity byToken = tokenServicel.getByToken(params.get("token").toString());
		UserEntity user = userService.getUserByUserId(byToken.getUserId());
		HashMap<String, Object> map = new HashMap<>();

		SdlPatientsEntity sdlPatientsEntity = sdlPatientsService.selectById(params.get("senderId").toString());
		sdlPatientsEntity.setBendBackPhoto(CompleteLinkUtils.CompleteLink(sdlPatientsEntity.getBendBackPhoto()));

		sdlPatientsEntity.setXPhoto(CompleteLinkUtils.CompleteLink(sdlPatientsEntity.getXPhoto()));

		sdlPatientsEntity.setRearPhoto(CompleteLinkUtils.CompleteLink(sdlPatientsEntity.getRearPhoto()));

		sdlPatientsEntity.setBendForwardPhoto(CompleteLinkUtils.CompleteLink(sdlPatientsEntity.getBendForwardPhoto()));

		sdlPatientsEntity.setRightFrontPhoto(CompleteLinkUtils.CompleteLink(sdlPatientsEntity.getRightFrontPhoto()));

		sdlPatientsEntity.setLeftSidePhoto(CompleteLinkUtils.CompleteLink(sdlPatientsEntity.getLeftSidePhoto()));

		sdlPatientsEntity.setRightSidePhoto(CompleteLinkUtils.CompleteLink(sdlPatientsEntity.getRightSidePhoto()));

		//获取背部照片对比数据

		//新建后弯腰照片集合
		ArrayList<BackPhotoVo> backPhotoVos = new ArrayList<>();
		//新建X光片集合
		ArrayList<XPhotoVo> xPhotoVos = new ArrayList<>();

		//初始照片
		BackPhotoVo backPhotoVo = new BackPhotoVo();
		backPhotoVo.setId(1);
		backPhotoVo.setUrl(sdlPatientsEntity.getBendBackPhoto());
		backPhotoVo.setName("后弯腰照(档案)");
		backPhotoVo.setProperty("剃刀背度数(胸): " + (sdlPatientsEntity.getRazorBack() != null ? sdlPatientsEntity.getRazorBack() : 0) + "°");
		backPhotoVo.setPropertyY("剃刀背度数(腰): " + (sdlPatientsEntity.getRazorBackY() != null ? sdlPatientsEntity.getRazorBackY() : 0) + "°");
		backPhotoVo.setFixed(true);
		backPhotoVos.add(backPhotoVo);

		XPhotoVo xPhotoVo = new XPhotoVo();
		xPhotoVo.setId(5);
		xPhotoVo.setUrl(sdlPatientsEntity.getXPhoto());
		xPhotoVo.setName("X光片(档案)");
		xPhotoVo.setCobb1("Cobb1: " + sdlPatientsEntity.getCobb1() + "°");
		xPhotoVo.setCobb2("Cobb1: " + sdlPatientsEntity.getCobb2() + "°");
		xPhotoVo.setCobb3("Cobb1: " + sdlPatientsEntity.getCobb3() + "°");
		xPhotoVo.setFixed(true);
		xPhotoVos.add(xPhotoVo);
		//获取复查记录
		List<SdlPatientsArchivesEntity> patientsArchivesEntityList = sdlPatientsArchivesService.getByPatientId(sdlPatientsEntity.getPatientsId());
		for (int i = 0; i < patientsArchivesEntityList.size(); i++) {

			BackPhotoVo backPhotoArchives = new BackPhotoVo();
			backPhotoArchives.setId(i + 2);
			backPhotoArchives.setUrl(CompleteLinkUtils.CompleteLink(patientsArchivesEntityList.get(i).getBendBackPhoto()));
			backPhotoArchives.setName("后弯腰照(复查)");
			backPhotoArchives.setProperty("剃刀背度数(胸): " + (patientsArchivesEntityList.get(i).getRazorBack() != null ? patientsArchivesEntityList.get(i).getRazorBack() : 0) + "°");
			backPhotoArchives.setPropertyY("剃刀背度数(腰): " + (patientsArchivesEntityList.get(i).getRazorBackY() != null ? patientsArchivesEntityList.get(i).getRazorBackY() : 0) + "°");
			backPhotoArchives.setFixed(true);

			backPhotoVos.add(backPhotoArchives);

			XPhotoVo xPhotoArchives = new XPhotoVo();
			xPhotoArchives.setId(i + 6);
			xPhotoArchives.setUrl(CompleteLinkUtils.CompleteLink(patientsArchivesEntityList.get(i).getXPhoto()));
			xPhotoArchives.setName("X光片(复查)");
			xPhotoArchives.setCobb1("Cobb1: " + patientsArchivesEntityList.get(i).getCobb1() + "°");
			xPhotoArchives.setCobb2("Cobb2: " + patientsArchivesEntityList.get(i).getCobb2() + "°");
			xPhotoArchives.setCobb3("Cobb3: " + patientsArchivesEntityList.get(i).getCobb3() + "°");
			xPhotoArchives.setFixed(true);

			xPhotoVos.add(xPhotoArchives);
		}

		sdlPatientsEntity.setImageLists(backPhotoVos);
		sdlPatientsEntity.setImageXList(xPhotoVos);
		//根据当前登录人来判断是否能修改
		if (user.getMobile().equals(sdlPatientsEntity.getUserPhone())) {
			map.put("isable", true);
		} else {
			map.put("isable", false);
		}
		map.put("patient", sdlPatientsEntity);
		return new Result().ok(map);
	}


	@PostMapping("souPatient")
	@Operation(summary = "修改/保存患者信息")
	public Result savePatient(@RequestBody SdlPatientsDTO sdlPatientsDTO) {

		TokenEntity byToken = tokenServicel.getByToken(sdlPatientsDTO.getToken());
		if (byToken != null) {
			UserEntity userByUserId = userService.getUserByUserId(byToken.getUserId());
			SdlPatientsEntity sdlPatientsEntity = ConvertUtils.sourceToTarget(sdlPatientsDTO, SdlPatientsEntity.class);


			if (sdlPatientsDTO.getPatientsId() != null && !sdlPatientsDTO.getPatientsId().equals("")) {
				sdlPatientsService.updateById(sdlPatientsEntity);
			} else {
				//根据身份证号限制
				List<SdlPatientsEntity> byIdCard = sdlPatientsService.getByIdCard(sdlPatientsDTO.getIdCard());
				if (byIdCard.size()>=1) {
					return new Result().error(401, "患者对应档案已存在");
				}
				//生成档案号
				sdlPatientsEntity.setMedicalNo(ArchiveNumberUtil.getInstance().generate());
				sdlPatientsEntity.setUserPhone(userByUserId.getMobile());
				sdlPatientsEntity.setCreater(byToken.getUserId());
				sdlPatientsEntity.setCreateTime(DateTime.now());
				sdlPatientsEntity.setIsDel(0);
				sdlPatientsService.insert(sdlPatientsEntity);
			}
			return new Result().ok(sdlPatientsEntity.getPatientsId());
		}

		return new Result().error(400, "长时间未操作,请重新登录");
	}


	@PostMapping("uploadPatient")
	@Operation(summary = "上传图片")
	public Result uploadPatient(@RequestParam(value = "file", required = false) MultipartFile file, String filedName, Long patientsId) {
		try {
			// 1. 保存文件并获取数据库记录
			SdlPatientsEntity patients = sdlPatientsService.saveUploadedFile(file, filedName, patientsId);

			// 2. 返回成功响应
			Map<String, Object> response = new HashMap<>();
			response.put("code", 200);
			response.put("message", "文件上传成功");
			response.put("data", patients);

			return new Result().ok(response);
		} catch (Exception e) {
			return new Result().error(500, "文件上传失败: " + e.getMessage());

		}
	}


	@PostMapping("deletePatient")
	@Operation(summary = "删除患者信息")
	public Result deletePatient(@RequestBody SdlPatientsDTO sdlPatientsDTO) {

		TokenEntity byToken = tokenServicel.getByToken(sdlPatientsDTO.getToken());
		if (byToken != null) {

			sdlPatientsService.deleteById(sdlPatientsDTO.getPatientsId());
			return new Result();
		}

		return new Result().error(400, "长时间未操作,请重新登录");
	}


}
